import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_text.dart';

class Spinner extends StatefulWidget {
  final List<Map> data; //数据
  final Function(int index) selectCallBack; //选中之后回调函数
  final int selectedIndex; //默认选中的值
  final Widget? leading; //前面的widget，一般是title
  final Widget? trailing; //尾部widget，一般是自定义图片
  final Color? textColor;
  final double offset; //下拉框向下偏移量--手动调整间距---防止下拉框遮盖住显示的widget
  final Color normalTextColor; //下拉框的文字样式
  final Color selectTextColor; //下拉框选中的文字样式
  final double maxHeight; //下拉框的最大高度
  final double maxWidth; //下拉框的最大宽度
  final Color? backGroundColor; //下拉框背景颜色
  final bool animation; //是否显示动画---尾部图片动画
  final int duration; //动画时长
  const Spinner({
    super.key,
    this.leading,
    required this.data,
    required this.selectCallBack,
    this.selectedIndex = 0,
    this.trailing,
    this.textColor = WColors.subTextColor,
    this.offset = 32,
    this.normalTextColor = WColors.mainTextColor,
    this.selectTextColor = WColors.primaryColor,
    this.maxHeight = 200.0,
    this.maxWidth = 300.0,
    this.backGroundColor = WColors.white,
    this.animation = true,
    this.duration = 200,
  });

  @override
  State<Spinner> createState() => _DropMenuWidgetState();
}

class _DropMenuWidgetState extends State<Spinner>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  String _selectedLabel = '';
  String _currentValue = '';

  // 是否展开下拉按钮
  bool _isExpand = false;

  @override
  void initState() {
    super.initState();

    if (widget.animation) {
      _animationController = AnimationController(
        vsync: this,
        duration: Duration(milliseconds: widget.duration),
      );
    }
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  _toggleExpand() {
    setState(() {
      if (_isExpand) {
        _animationController.forward();
      } else {
        _animationController.reverse();
      }
    });
  }

  //根据传值处理显示的文字
  _initLabel() {
    if (widget.data.isEmpty) {
      return;
    }
    _selectedLabel = widget.data[widget.selectedIndex]['label'];
    _currentValue = widget.data[widget.selectedIndex]['value'];
  }

  @override
  Widget build(BuildContext context) {
    _initLabel();
    return PopupMenuButton(
      constraints: BoxConstraints(
          maxHeight: widget.maxHeight.px,
          maxWidth: widget.maxWidth.px,
          minWidth: 100.px),
      padding: EdgeInsets.zero,
      shadowColor: WColors.white,
      surfaceTintColor: WColors.white,
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
      offset: Offset(0, widget.offset.px),
      color: widget.backGroundColor,
      onOpened: () {
        if (widget.animation) {
          setState(() {
            _isExpand = true;
            _toggleExpand();
          });
        }
      },
      onCanceled: () {
        if (widget.animation) {
          setState(() {
            _isExpand = false;
            _toggleExpand();
          });
        }
      },
      child: FittedBox(
        //使用FittedBox是为了适配当字符串长度超过指定宽度的时候，会让字体自动缩小
        child: Row(
          children: [
            if (widget.leading != null) widget.leading!,
            Text(
              _selectedLabel,
              style: TextStyle(
                color: widget.textColor,
                fontSize: WDimens.tsMedium,
              ),
            ),
            widget.trailing ??
                Image.asset(
                  "images/ic_right.png",
                  color: WColors.CCCCCCC,
                  width: 14.px,
                ),
          ],
        ),
      ),
      itemBuilder: (context) {
        return widget.data.map((e) {
          return PopupMenuItem(
            height: 40.px,
              padding: EdgeInsets.zero,
            child: Container(
              width: double.infinity,
              height: 40.px,
              alignment: Alignment.center,
              color:
                  e['value'] == _currentValue ? WColors.CF8F9FA : WColors.white,
              child: WText(e['label'],
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      fontSize: 14.px,
                      color: e['value'] == _currentValue
                          ? widget.selectTextColor
                          : widget.normalTextColor)),
            ),
            onTap: () {
              setState(() {
                _currentValue = e['value'];
                widget.selectCallBack(geIndex(e['value']));
              });
            },
          );
        }).toList();
      },
    );
  }

  int geIndex(String value) {
    for (int i = 0; i < widget.data.length; i++) {
      if (widget.data[i]["value"] == value) {
        return i;
      }
    }
    return -1;
  }
}
